package handlers

import (
	"context"
	"errors"
	"strings"
	"zong-microservice/app/models"
	"zong-microservice/app/services/auth/proto"
	"zong-microservice/pkg/auth"
	"zong-microservice/pkg/config"
	"zong-microservice/pkg/helper"
)

type AuthHandler struct {
	userModel models.User
}

// Login 用户登录
func (handler *AuthHandler) Login(context context.Context, req *proto.LoginRequest, resp *proto.LoginResponse) error {
	if u, err := handler.userModel.GetByUsername(req.Username); err != nil {
		resp.Code = 1
		resp.Message = "用户不存在"
		return err
	} else {
		if ok := u.ComparePassword(req.Password); !ok {
			resp.Code = 1
			resp.Message = "用户密码错误"
			return errors.New("User password error.")
		}
		// 获取 token 并存入 session
		token := auth.GetToken(u)

		resp.Data = &proto.LoginResponse_Data{
			AccessToken: token,
			TokenType:   "Bearer",
			ExpiresIn:   int64(helper.StringToInt(config.Get("jwt", "expires")) * 60),
		}
		resp.Code = 0
		resp.Message = "success"

		return nil
	}
}

// Logout 用户退出
func (handler *AuthHandler) Logout(context context.Context, req *proto.LogoutRequest, resp *proto.LogoutResponse) error {
	// 删除 token 实际是刷新 token 但是不返回
	authorization := req.AccessToken
	auth.FlushToken(strings.Fields(authorization)[1], handler.userModel)

	resp.Code = 0
	resp.Message = "success"

	return nil
}

// Refresh 用户刷新token
func (handler *AuthHandler) Refresh(context context.Context, req *proto.RefreshRequest, resp *proto.RefreshResponse) error {
	authorization := req.AccessToken
	token := auth.RefreshToken(strings.Fields(authorization)[1], handler.userModel)

	resp.Data = &proto.RefreshResponse_Data{
		AccessToken: token,
		TokenType:   "Bearer",
		ExpiresIn:   int64(helper.StringToInt(config.Get("jwt", "expires")) * 60),
	}
	resp.Code = 0
	resp.Message = "success"

	return nil
}
